package properties

class PetController {

    static allowedMethods = [update: "POST"]

    def index = {
        redirect(action: "show")
    }

    def show = {
        def PETInstance = PET.list(max:1)?.get(0)
        if (!PETInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'PET.label', default: 'PET'), params.id])}"
            redirect(controller: "index")
        }
        else {
            [PETInstance: PETInstance]
        }
    }

    def edit = {
        def PETInstance = PET.list(max:1)?.get(0)
        if (!PETInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'PET.label', default: 'PET'), params.id])}"
            redirect(action: "show")
        }
        else {
            return [PETInstance: PETInstance]
        }
    }

    def update = {
        def PETInstance = PET.get(params.id)
        if (PETInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (PETInstance.version > version) {
                    PETInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'PET.label', default: 'PET')] as Object[], "Another user has updated this PET while you were editing")
                    render(view: "edit", model: [PETInstance: PETInstance])
                    return
                }
            }
            PETInstance.properties = params
            if (!PETInstance.hasErrors() && PETInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'PET.label', default: 'PET'), PETInstance.id])}"
                redirect(action: "show", id: PETInstance.id)
            }
            else {
                render(view: "edit", model: [PETInstance: PETInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'PET.label', default: 'PET'), params.id])}"
            redirect(action: "show")
        }
    }

}
